﻿using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace RBOSS.Utilities
{
    public class RBOSSecurity
    {
        private static readonly byte[] Key = { 1, 22, 99, 14, 14, 39, 5, 19, 21, 9, 20, 58, 20, 18, 9, 16, 12, 54, 4, 5, 19, 22, 5, 67 };
        private static readonly byte[] Iv = { 13, 49, 49, 41, 64, 63, 72, 82 };

        private static byte[] EncrypAstTripleDES(string inputString)
        {
            var sym = new TripleDESCryptoServiceProvider();
            var utf8Encoder = new UTF8Encoding();
            byte[] inputBytes = utf8Encoder.GetBytes(inputString);
            var cryptoTransform = sym.CreateEncryptor(Key, Iv);
            var ms = new MemoryStream();
            var encStream = new CryptoStream(ms, cryptoTransform, CryptoStreamMode.Write);
            encStream.Write(inputBytes, 0, inputBytes.Length);
            encStream.FlushFinalBlock();
            ms.Position = 0;
            var result = new byte[ms.Length];
            ms.Read(result, 0, Convert.ToInt32(ms.Length));
            encStream.Close();
            ms.Close();

            return result;
        }

        public static string Encrypt(string inputString)
        {
            var myitems = EncrypAstTripleDES(inputString);
            return BitConverter.ToString(myitems).Replace("-", "");
        }

        public static string Decrypt(byte[] inputBytes)
        {
            var sym = new TripleDESCryptoServiceProvider();
            var cryptoTransform = sym.CreateDecryptor(Key, Iv);
            var ms = new MemoryStream();
            var decStream = new CryptoStream(ms, cryptoTransform, CryptoStreamMode.Write);
            decStream.Write(inputBytes, 0, inputBytes.Length);
            decStream.FlushFinalBlock();
            ms.Position = 0;
            var result = new byte[ms.Length];
            ms.Read(result, 0, Convert.ToInt32(ms.Length));
            decStream.Close();
            ms.Close();
            var utf8Encoder = new UTF8Encoding();

            return utf8Encoder.GetString(result);
        }

        public static string Decrypt(string arrayOfBytesAsString)
        {
            var b = new byte[(arrayOfBytesAsString.Length / 2)];
            for (var i = 0; i <= b.GetUpperBound(0); i++)
            {
                b[i] = byte.Parse(arrayOfBytesAsString.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber);
            }

            return Decrypt(b);
        }
    }


}
